import { constantRoutes } from '@/router';

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion 前端鉴权，通过角色过滤 有权限的菜单
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(routes, menus) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(menus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus);
      }
      res.push(tmp);
    }
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRouters = routes;
    state.routes = constantRoutes.concat(routes);
  }
};

// 通过菜单转化成路由表
const actions = {
  //     generateRoutes({ commit }, menus) {
  //         return new Promise((resolve) => {
  //             const accessedRoutes = filterAsyncRoutes(asyncRoutes, menus);
  //             commit('SET_ROUTES', accessedRoutes);
  //             resolve();
  //         });
  //     }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
